import { Component } from '@angular/core';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { _HttpClient } from '@delon/theme';
import { EditComponent } from 'src/app/routes/common/edit/edit.component';
import { SysRoleService } from '@api/sys/service/sysRole.service';
import { SimpleAction } from '@api/simple/model/simpleAction.model';
import { SysKeyValue } from '@api/sys/model/sysKeyValue.model';

@Component({
  selector: 'app-simple-action-edit',
  templateUrl: './edit.component.html',
})
export class SimpleActionEditComponent extends EditComponent<SimpleAction, String> {
  checked = false;
  loading = false;
  indeterminate = false;
  setOfCheckedId = new Set<string>();

  actionTyps: SysKeyValue[] = [];

  constructor(public modal: NzModalRef, public msgSrv: NzMessageService, public http: _HttpClient, public sysRoleService: SysRoleService) {
    super(modal, msgSrv, http, sysRoleService);
    this.schema = {
      properties: {
        code: { type: 'string', title: '代码' },
        name: { type: 'string', title: '名称', maxLength: 30 },
        sort: { type: 'integer', title: '排序' },
      },
      required: ['code', 'name'],
    };
    this.ui = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 12 },
      },
    };
  }

  updateCheckedSet(id: string, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.i.fields;
    this.checked = listOfEnabledData.every((item: any) => this.setOfCheckedId.has(item.id));
    this.indeterminate = listOfEnabledData.some((item: any) => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  onItemChecked(id: string, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(checked: boolean): void {
    this.i.fields.forEach((item: any) => this.updateCheckedSet(item.id, checked));
    this.refreshCheckedStatus();
  }

  addLine() {
    this.i.fields.push({
      id: `${new Date().getTime()}`,
      type: 'string',
      fixed: '',
    });
  }

  deleteLine() {
    this.i.fields.splice(this.i.fields.findIndex((item: any) => this.setOfCheckedId.has(item.id!), 1));
    this.setOfCheckedId.clear();
  }
}
